$(function(){
	//Set数据结构存放所有题型信息
	qtSet=new Set();
	//存放所有知识点信息
	kps=new Array();
	//存放传给后台的所有数据
	resultMap={};
	orderFlag=true,scoresFlag=true;
	
	//设置题型信息
	//$("#subjectSelect").change(function(){
		getAllKps();
		getQuesCount1();
	//})
	
	//点击生成试卷按钮
	$("#generate_paper_button").click(function(){
		generateButtonClick();
	})
	
})

//画知识点信息
function getAllKps(){

    $.getJSON('Kld/selectAllLev/0', function (res) {
        var qxid = $('#questCatagory');

        $.each(res, function (index,item) {
            console.log('%i - %o', index, item);
            qxid.append('<option value="' + item.levKldID +'">' + item.levKldCtgr + '</option>');
        })
    });

    // 加二级知识点下拉列表
    function changeLevKld(ele) {
        var  levKldID= ele.options[ele.selectedIndex].value;
        $.getJSON('Kld/selectAllSecByLevID/0',{levKldID:  levKldID},function (res) {
            var secKldIDFrom = $('#secKldIDFrom');
            secKldIDFrom.empty();
            $.each(res, function (index,item) {
                console.log('%i - %o', index, item);
                secKldIDFrom.append('<option value="' + item.secKldID +'">' + item.secKldCtgr + '</option>');
            })
        });
    }
    // 将选中的知识点添加到提交处
    function addSecTo(secKldIDFrom,secKldIDTo,msg) {

        var secKldIDFrom = $("#" + secKldIDFrom);
        console.log(secKldIDFrom);
        var secKldIDTo = $("#" + secKldIDTo);
        var fromValue = secKldIDFrom.val() == null ? "" : $.trim(secKldIDFrom.val());// 获取select选择的或者text的value
        if (fromValue == ""||fromValue=="请选择..") {
            alert(msg);
            return;
        }
        if(secKldIDTo.find("option[value='"+fromValue+"']")[0]){
            alert("不能重复添加！");
            return;
        }

        var	secKldCtgr = secKldIDFrom.find("option:selected").text();// 获取select选择的text
        var secKldID = secKldIDFrom.find("option:selected").val();// 获取select选择的code
        secKldIDTo.append('<option value="' + secKldID +'">' + secKldCtgr + '</option>');// 为select追加一个option(下拉项)
        secKldIDTo.get(0).selectedIndex = 0;// 设置select索引值为0的项选中

    }
    // 删除select的option
    function delSec(secKldIDTo, msg) {
        var select = $("#" + secKldIDTo);
        var toValue = select.val() == null ? "" : $.trim(select.val());
        if (toValue == "") {
            alert(msg);
        } else {
            select.find("option[value='" + select.val() + "']").remove();// 删除select中选择的option
        }

    }

  /*  $.ajax({
			url:"knowledgPoints/",
			method:"get",
			success:function(data){
				var knows=data.map.knows;
				
				$("#kp_div .modal-body").html("");
				for(var i in knows){
					if(knows[i].kSubNum==0){
						$("#kp_div .modal-body").append("<label><input name='konwledgePoint' class='kpF"+knows[i].kNum+"' type='checkbox' value="+knows[i].kId+">"+knows[i].kNum+"."+knows[i].kSubNum+"."+knows[i].kTitle+"</label>");
					}else{
						$("#kp_div .modal-body").append("<label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input name='konwledgePoint' class='kpS"+knows[i].kNum+"' type='checkbox' value="+knows[i].kId+">"+knows[i].kNum+"."+knows[i].kSubNum+"."+knows[i].kTitle+"</label>");
					}
				}
				
				if(knows!=""){
					$("#kp_div .modal-body").append("<button class='btn btn-default' data-dismiss='modal' id='kp_button_commit'>确认</button>")
				}
				//全选功能
				clickAll();
				
				//选择知识点范围
				$("#kp_button_commit").click(function(){
					kpButtonClick();
				})
			},
			error:function(){
			}
		})*/
		
}

//选择知识点范围
$("#kp_button_commit").click(function(){
    kpButtonClick();
})

//知识点确定点击方法---查询条件限制：科目，知识点
function kpButtonClick(){
	//先清空知识点
	kps=[];
	$("input[name='konwledgePoint']:checked").each(function(){
//		console.log($(this).val())
		kps.push($(this).val())
	})
	
	//console.log(kps)
	
	var data={
		"kps":kps
	}
	//生成json数据
	var jsonData=JSON.stringify(data);
	
	$.ajax({
		url:'amount/',
		method:'post',
		contentType: "application/json; charset=utf-8",
		data:jsonData,
		success:function(data){
			//解析数据
			parseData(data);
		},
		error:function(){}
		
	})
}


//解析--getQuesCount1--方法数据
function parseData(data){
	//console.log(data)
	var map1=data.list[0];
	var map2=data.list[1];
	//题型种类
	var qtlength=Object.keys(map2).length;
	
	//将总的题目个数和总分清0
	$("#total_ques").text("0")
	$("#total_score").text("0")
	
	$.each(map1,function(key,value){
		//设置题目个数信息
		$("#qt_"+key).text(value);
	})
	
	$.each(map2,function(key,value){
		qtSet.add(key)
		
		//将个题型总分清0
		$("#set_qt_"+key+"_total_score").text("0")
		
		//设置试题顺序的select
		$("#set_qt_"+key+"_order").html("");
		for(var i=0;i<=qtlength;i++){
			//console.log("key1---key::"+"#set_qt_"+key1+"_order")
			$("#set_qt_"+key+"_order").append("<option value="+key+">"+i+"</option>");
		}
		
		//设置--用户选择--不同题型的个数
		$("#set_qt_"+key+"_num").html("");
		for(var i=0;i<=value;i++){
			$("#set_qt_"+key+"_num").append("<option value="+key+">"+i+"</option>");
		}
		
		//不同题型的分值
		$("#set_qt_"+key+"_score").html("");
		for(var i=0;i<=100;i++){
			$("#set_qt_"+key+"_score").append("<option value="+key+">"+i+"</option>");
		}
		
	})
	
	//题目数量的select改变
	$("select[name='changes_num']").change(function(){
		var quesType=$(this).val();
		var id=$(this).attr("id");
		var quesTypeNum=$.trim($("#"+id+" option:selected").text());
		//console.log(quesType+":num:"+quesTypeNum)
		var quesTypeScore=$.trim($("#set_qt_"+quesType+"_score option:selected").text());
		//console.log(quesTypeNum+"   "+quesTypeScore+"  "+$.trim($("#set_qt_"+quesType+"_total_score").text()))
		$("#set_qt_"+quesType+"_total_score").text(quesTypeNum*quesTypeScore)
		
		var nums=0,totalScore=0;
		//qtSet中存放所有题型
		qtSet.forEach(function(item){
			nums+=parseInt($.trim($("#set_qt_"+item+"_num option:selected").text()));
			totalScore+=parseInt($.trim($("#set_qt_"+item+"_total_score").text()));
		})
		
		//console.log("totalScore:"+nums+"   "+totalScore)
		$("#total_ques").text(nums)
		$("#total_score").text(totalScore)
		
	})
	
	//题型分数的select改变
	$("select[name='changes_score']").change(function(){
		var quesType=$(this).val();
		var id=$(this).attr("id");
		var quesTypeScore=$.trim($("#"+id+" option:selected").text());
		//console.log(quesType+":score:"+quesTypeScore)
		var quesTypeNum=$.trim($("#set_qt_"+quesType+"_num option:selected").text());
		//console.log(quesTypeNum+"   "+quesTypeScore+"  "+$("#set_qt_"+quesType+"_total_score").text())
		$("#set_qt_"+quesType+"_total_score").text(quesTypeNum*quesTypeScore)
		
		var totalScore=0;
		//qtSet中存放所有题型
		qtSet.forEach(function(item){
			totalScore+=parseInt($.trim($("#set_qt_"+item+"_total_score").text()));
		})
		//console.log("totalScore："+totalScore)
		$("#total_score").text(totalScore)
	})
}

//点击生成试卷按钮
function generateButtonClick(){

	var paperDiffLev= $("#paper_difficulty_level").val();
	var qtNum,qtScore,qtTotalScore,nunms,scores;
    kps=[];
    var kp = secKldIDFrom.find("option:selected").val();
    //console.log($(this).val())
    $("select[name='secKld']:selected").each(function(){
		console.log($(this).val())
        kps.push($(this).val())
    })

    /*tempMap={};
    tempMap["qtId"]=item;
    tempMap["qtNum"]=qtNum;
    tempMap["qtScore"]=qtScore;
    qtList.push(tempMap)*/

	//存放试题信息
	/*qtList=new Array();
	
	$("#paper_table").html("")
	$("#paper_table").append("<th colspan='5'>&nbsp;&nbsp;&nbsp;&nbsp;试卷难度："+paperDiffLev+"</th>")
	$("#paper_table").append("<tr>" +
			"<td>题型</td>" +
			"<td>题目个数</td>" +
			"<td>分值</td>" +
			
			"<td>该题型总分</td>" +
			"</tr>")
	
	//循环之前清空resultList
		
	qtSet.forEach(function(item){
		//用每个题型总分作为判断依据
		if($.trim($("#set_qt_"+item+"_total_score").text())!=0){
			qtNum=$.trim($("#set_qt_"+item+"_num option:selected").text());
			qtScore=$.trim($("#set_qt_"+item+"_score option:selected").text());
			qtTotalScore=$.trim($("#set_qt_"+item+"_total_score").text());
			
			tempMap={};
			tempMap["qtId"]=item;
			tempMap["qtNum"]=qtNum;
			tempMap["qtScore"]=qtScore;
			qtList.push(tempMap)
			
			$("#paper_table").append("<tr name='"+item+"'>" +
					"<td>"+qtNum+"</td>" +
					"<td>"+qtScore+"</td>" +
					"<td>"+qtTotalScore+"</td>" +
					"</tr>")
		}
		
	})
	
	nums=$.trim($("#total_ques").text());
	scores=$.trim($("#total_score").text());
	$("#paper_table").append("<tr>" +
			"<td>总计</td>" +
			"<td>"+nums+"</td>" +
			"<td></td>" +
			"<td></td>" +
			"<td>"+scores+"</td>" +
			"</tr>")
	$("#paper_table").append("<tr><td colspan='5'><button style='margin-left:40%' class='btn btn-default' id='generatePaper'>确认生成</button></td></tr>")
	*/
    scores=$("total_scores").val;
	//先将resultMap清空
	resultMap={};	
//	resultMap.set("qtList",qtList);
//	resultMap.set("totalScore",scores);
	//resultMap["qtList"]=qtList;
	resultMap["totalScore"]=scores;
	
	//第二次改变会保持false
	scoresFlag=true
	if(Number(scores)<=0){
		scoresFlag=false;
	}
	
	//确认生成试卷--ajax
	$("#generatePaper").click(function(){
		generatePaper();
	})
}

//生成试卷
function generatePaper(){
		var paperDiffLev= $("#paper_difficulty_level").val();
		var paperDiffFalg=true;

		if(paperDiffLev==""){
			paperDiffFalg=false;
			alert("请填写试卷难度系数")
		}else{
				paperDiffLev=Number(paperDiffLev);
				//Number.NAN--Not a Number
				if(isNaN(paperDiffLev)){
					alert("试卷难度系数格式错误")
					paperDiffFalg=false;
					
				}else if(paperDiffLev<0||paperDiffLev>1){
					alert("试卷难度必须位于0-1之间")
					paperDiffFalg=false;
				}
			
		}
		
		if(!scoresFlag){
			alert("总分不能为空，请选择试题信息");
		}
		
		if(paperDiffFalg&&scoresFlag){
			resultMap["paperDiffLev"]=paperDiffLev;

			resultMap["kps"]=kps;
			
			console.log(resultMap)
			var jsonData=JSON.stringify(resultMap);
			//console.log(jsonData)
			
			
			$.ajax({
				url:'generatePaperAuto',
				method:'post',
				contentType: "application/json; charset=utf-8",
				data:jsonData,
				success:function(data){
					//alert(data)
					if(data.rtnCode=="-9999"){
						alert(data.rtnMessage)
					}
					if(data.rtnCode=="0"){
						if(confirm(data.rtnMessage)){
							//点击确定按钮
							window.location.href="views/exam/test.jsp"
						}
					}
				},
				error:function(){
					alert("error");
				}
			})
			
		}
		
}
